package jmine.tec.web.wicket.component.menu;

import static jmine.tec.web.wicket.pages.main.ExternalPage.SOURCE_URL;
import jmine.tec.web.tags.BreadCrumbTag;
import jmine.tec.web.wicket.pages.main.ExternalPage;

import org.apache.wicket.PageParameters;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.protocol.http.WebRequest;

/**
 * @author lundberg
 */
public class MenuJSFLink extends MenuLink {

    private final String destination;

    /**
     * Construtor.
     * 
     * @param caption caption
     * @param destination destination
     */
    public MenuJSFLink(String caption, String destination) {
        super(caption);
        this.destination = destination;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public AbstractLink getLink() {

        PageParameters parameters = new PageParameters();
        parameters.add(SOURCE_URL, this.getDestinationURL());

        AbstractLink link = new BookmarkablePageLink<ExternalPage>("link", ExternalPage.class, parameters);
        link.setMarkupId(this.destination.substring(1).replaceAll("/", "_") + "_link");
        link.setOutputMarkupId(true);
        link.add(new Label("caption", this.getCaption()));

        return link;
    }

    /**
     * Define a url externa de destino, incluido filtro de session clean, bread crumb e limpeza de caracteres especiais.
     * 
     * @return a url de destino.
     */
    public String getDestinationURL() {
        StringBuilder dest = new StringBuilder();
        dest.append(((WebRequest) RequestCycle.get().getRequest()).getHttpServletRequest().getContextPath());
        dest.append(this.destination);
        dest.append('?').append("SessionCleanerFilter.CLEAN=1");
        String menuItemId = this.getPath().replace("&", "%26");
        dest.append('&').append(BreadCrumbTag.REQUEST_KEY).append('=').append(menuItemId);
        return dest.toString();
    }
}
